/*
 * Copyright (c) 2012 Universidad Antonio de Nebrija.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Apache License v2.0
 * which accompanies this distribution, and is available at
 * http://www.apache.org/licenses/LICENSE-2.0.html
 * 
 * Contributors:
 *    Universidad Antonio de Nebrija - initial API, implementation and documentation
 */
package com.nebrija.riif.cli;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;


import com.nebrija.riif.model.Component;
import com.nebrija.riif.model.RootClass;
import com.nebrija.riif.model.saver.bufferedwriter.RIIFWriterFormatSaverFactory;

/**
 * Command to save a component to a RIIF file
 * @author asanchep
 *
 */
public class SaveCommand implements Command {

		@Override
	public String execute(ArrayList<String> params) throws CommandException {
		if (params.size()<2){
			throw new CommandException (CommandException.NOT_ENOUGH_PARAMS);
		}
		
		String componentName = params.get(0);
		String filename = params.get(1);

		RootClass r = RootClass.getInstance();
		Component c = (Component) r.getElement(componentName);
		BufferedWriter out = null;
		try{
			 out = new BufferedWriter(new FileWriter(filename));
			RIIFWriterFormatSaverFactory factory = 
					new RIIFWriterFormatSaverFactory(out);
			factory.getComponentSaver().save(c);
			out.close();
		}catch (IOException ioe) {
			try{
				out.close();
			}catch(Exception ex){}
			
			throw new CommandException (ioe.getMessage());
		}
		return "Command Completed";
	}

	@Override
	public String helpString() throws CommandException {
		return " <component> <filename>  :  write a component to a RIIF file";
	}

}
